package org.example.lua;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.util.Arrays;

/**
 * @FileName LuaService
 * @Description
 * @Author coderfun
 * @selfDesc coding in fun
 * @date 2024-11-07
 **/
@Service
public class LuaService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // lua关于单步骤执行incr的命令的脚本
    private static final String LUA_SCRIPT =
            "local key = KEYS[1]\n" +
                    "local field = ARGV[1]\n" +
                    "local increment = tonumber(ARGV[2])\n" +
                    "local result = redis.call('HINCRBY', key, field, increment)\n" +
                    "return result";

    public Long hIncrByWithLua(String key, String field, long increment) {
        // 创建 RedisScript 对象
        RedisScript<Long> redisScript = RedisScript.of(LUA_SCRIPT, Long.class);

        // 执行 Lua 脚本
        Object result = stringRedisTemplate.execute(
                redisScript,
                Arrays.asList(key),
                field, String.valueOf(increment)
        );

        return (Long) result;
    }
}
